In this project, you will apply unsupervised learning techniques to identify segments of the population that form the core customer base for a mail-order sales company in Germany. These segments can then be used to direct marketing campaigns towards audiences that will have the highest expected rate of returns. The data that you will use has been provided by our partners at Bertelsmann Arvato Analytics, and represents a real-life data science task.
This notebook will help you complete this task by providing a framework within which you will perform your analysis steps. In each step of the project, you will see some text describing the subtask that you will perform, followed by one or more code cells for you to complete your work. Feel free to add additional code and markdown cells as you go along so that you can explore everything in precise chunks. The code cells provided in the base template will outline only the major tasks, and will usually not be enough to cover all of the minor tasks that comprise it.
It should be noted that while there will be precise guidelines on how you should handle certain tasks in the project, there will also be places where an exact specification is not provided. There will be times in the project where you will need to make and justify your own decisions on how to treat the data. These are places where there may not be only one way to handle the data. In real-life tasks, there may be many valid ways to approach an analysis task. One of the most important things you can do is clearly document your approach so that other scientists can understand the decisions you've made.
At the end of most sections, there will be a Markdown cell labeled Discussion. In these cells, you will report your findings for the completed section, as well as document the decisions that you made in your approach to each subtask. Your project will be evaluated not just on the code used to complete the tasks outlined, but also your communication about your observations and conclusions at each stage.
# import libraries here; add more as necessary
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
import ast
import plotly.graph_objs as go
from sklearn.preprocessing import Imputer, StandardScaler
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
# magic word for producing visualizations in notebook
%matplotlib inline
There are four files associated with this project (not including this one):
Udacity_AZDIAS_Subset.csv: Demographics data for the general population of Germany; 891211 persons (rows) x 85 features (columns).Udacity_CUSTOMERS_Subset.csv: Demographics data for customers of a mail-order company; 191652 persons (rows) x 85 features (columns).Data_Dictionary.md: Detailed information file about the features in the provided datasets.AZDIAS_Feature_Summary.csv: Summary of feature attributes for demographics data; 85 features (rows) x 4 columnsEach row of the demographics files represents a single person, but also includes information outside of individuals, including information about their household, building, and neighborhood. You will use this information to cluster the general population into groups with similar demographic properties. Then, you will see how the people in the customers dataset fit into those created clusters. The hope here is that certain clusters are over-represented in the customers data, as compared to the general population; those over-represented clusters will be assumed to be part of the core userbase. This information can then be used for further applications, such as targeting for a marketing campaign.
To start off with, load in the demographics data for the general population into a pandas DataFrame, and do the same for the feature attributes summary. Note for all of the .csv data files in this project: they're semicolon (;) delimited, so you'll need an additional argument in your read_csv() call to read in the data properly. Also, considering the size of the main dataset, it may take some time for it to load completely.
Once the dataset is loaded, it's recommended that you take a little bit of time just browsing the general structure of the dataset and feature summary file. You'll be getting deep into the innards of the cleaning in the first major step of the project, so gaining some general familiarity can help you get your bearings.
# Load in the general demographics data.
azdias = pd.read_csv('Udacity_AZDIAS_Subset.csv', delimiter=';')
# Load in the feature summary file.
feat_info = pd.read_csv('AZDIAS_Feature_Summary.csv', delimiter=';')
# Check the structure of the data after it's loaded (e.g. print the number of
# rows and columns, print the first few rows).
rows = len(azdias)
columns = len(azdias.columns)
print('number of rows: {}'.format(rows))
print('number of columns: {}'.format(columns))
azdias.head()
azdias.columns
feat_info
Tip: Add additional cells to keep everything in reasonably-sized chunks! Keyboard shortcut
esc --> a(press escape to enter command mode, then press the 'A' key) adds a new cell before the active cell, andesc --> badds a new cell after the active cell. If you need to convert an active cell to a markdown cell, useesc --> mand to convert to a code cell, useesc --> y.
The feature summary file contains a summary of properties for each demographics data column. You will use this file to help you make cleaning decisions during this stage of the project. First of all, you should assess the demographics data in terms of missing data. Pay attention to the following points as you perform your analysis, and take notes on what you observe. Make sure that you fill in the Discussion cell with your findings and decisions at the end of each step that has one!
The fourth column of the feature attributes summary (loaded in above as feat_info) documents the codes from the data dictionary that indicate missing or unknown data. While the file encodes this as a list (e.g. [-1,0]), this will get read in as a string object. You'll need to do a little bit of parsing to make use of it to identify and clean the data. Convert data that matches a 'missing' or 'unknown' value code into a numpy NaN value. You might want to see how much data takes on a 'missing' or 'unknown' code, and how much data is naturally missing, as a point of interest.
As one more reminder, you are encouraged to add additional cells to break up your analysis into manageable chunks.
# Identify missing or unknown data values and convert them to NaNs.
#grouping by missing or unkown types
feat_nan_types = feat_info[['missing_or_unknown',
'attribute']].groupby('missing_or_unknown')['attribute'].apply(list).reset_index()
#replacing values which cannot be converted to list by default
feat_nan_types['missing_or_unknown'].replace({'[-1,X]': '[-1,"X"]',
'[-1,XX]': '[-1,"XX"]',
'[XX]': '["XX"]'}, inplace = True)
#converting missing types to lists
feat_nan_types['missing_or_unknown'] = feat_nan_types['missing_or_unknown'].apply(lambda feat: ast.literal_eval(feat))
# filtering main dataframe and converting appropriate values to np.nan
for feat, attr in zip(feat_nan_types['missing_or_unknown'], feat_nan_types['attribute']):
azdias[attr] = azdias[attr].applymap(lambda value: np.nan if value in feat else value)
How much missing data is present in each column? There are a few columns that are outliers in terms of the proportion of values that are missing. You will want to use matplotlib's hist() function to visualize the distribution of missing value counts to find these columns. Identify and document these columns. While some of these columns might have justifications for keeping or re-encoding the data, for this project you should just remove them from the dataframe. (Feel free to make remarks about these outlier columns in the discussion, however!)
For the remaining features, are there any patterns in which columns have, or share, missing data?
# Perform an assessment of how much missing data there is in each column of the
# dataset.
feat_info['NULL_Value'] = feat_info['attribute'].apply(lambda attr: len(azdias[attr][azdias[attr].isnull()]))
feat_info['NULL_RATIO'] = feat_info['attribute'].apply(lambda attr:
len(azdias[attr][azdias[attr].isnull()]) / len(azdias[attr]) )
# Investigate patterns in the amount of missing data in each column.
feat_info.sort_values('NULL_RATIO' , ascending=False, inplace=True)
data = [go.Bar(
x=feat_info['attribute'],
y=feat_info['NULL_RATIO']
)]
layout= dict(title = 'Distribution of null value ratios for all columns',
xaxis = dict(title = 'Attributes'),
yaxis = dict(title = 'Null Value Ratio'))
fig = go.Figure(data=data, layout=layout)
iplot(fig)
levels = list(feat_info['information_level'].drop_duplicates())
for level in levels:
data = [go.Bar(
x=feat_info['attribute'][feat_info['information_level']==level],
y=feat_info['NULL_Value'][feat_info['information_level']==level]
)]
layout= dict(title = 'Distribution of null value rows for all columns within {} feature group'.format(level),
xaxis = dict(title = 'Attributes'),
yaxis = dict(title = 'Null Value count'))
fig = go.Figure(data=data, layout=layout)
iplot(fig)
# Remove the outlier columns from the dataset. (You'll perform other data
# engineering tasks such as re-encoding and imputation later.)
feat_info_columns = feat_info['attribute'][feat_info['NULL_RATIO']<0.18].values.tolist()
azdias = azdias[feat_info_columns].copy()
(Double click this cell and replace this text with your own text, reporting your observations regarding the amount of missing data in each column. Are there any patterns in missing values? Which columns were removed from the dataset?)
There are six columns where the ratio of the Null values was above 18 % of the total row count in the column. These were removed . The column names are: 'TITEL_KZ', 'AGER_TYP', 'KK_KUNDENTYP', 'KBA05_BAUMAX', 'GEBURTSJAHR', 'ALTER_HH' For the rest of the columns while null values are present, removing them would probably cause to information loss.
In terms of patterns for the missing values we can observe that the ratio of null values show similar characteristics for the attributes within their particular information level groups. From this we can assume that the data have been collected and assebled by feature level
Now, you'll perform a similar assessment for the rows of the dataset. How much data is missing in each row? As with the columns, you should see some groups of points that have a very different numbers of missing values. Divide the data into two subsets: one for data points that are above some threshold for missing values, and a second subset for points below that threshold.
In order to know what to do with the outlier rows, we should see if the distribution of data values on columns that are not missing data (or are missing very little data) are similar or different between the two groups. Select at least five of these columns and compare the distribution of values.
countplot() function to create a bar chart of code frequencies and matplotlib's subplot() function to put bar charts for the two subplots side by side.Depending on what you observe in your comparison, this will have implications on how you approach your conclusions later in the analysis. If the distributions of non-missing features look similar between the data with many missing values and the data with few or no missing values, then we could argue that simply dropping those points from the analysis won't present a major issue. On the other hand, if the data with many missing values looks very different from the data with few or no missing values, then we should make a note on those data as special. We'll revisit these data later on. Either way, you should continue your analysis for now using just the subset of the data with few or no missing values.
# How much data is missing in each row of the dataset?
azdias['missing_value'] = azdias.isnull().sum(axis=1)
data = [go.Histogram(x=azdias['missing_value'])]
layout= dict(title = 'Distribution of null value count within rows',
xaxis = dict(title = 'Number of rows containing null values'),
yaxis = dict(title = 'Value count'))
fig = go.Figure(data=data, layout=layout)
iplot(fig)
# Write code to divide the data into two subsets based on the number of missing
# values in each row.
azdias_1 = azdias[azdias['missing_value'] <= 15].copy()
azdias_2 = azdias[azdias['missing_value'] > 15].copy()
def plot_distribution(column):
trace1 = go.Histogram(x=azdias_1[column],
name='missing_value <= 15'
)
trace2 = go.Histogram(x=azdias_2[column],
name='missing_value >= 15'
)
data = [trace1, trace2]
layout= dict(title = 'Distribution of values for two subset for column {}'.format(column),
xaxis = dict(title = 'values in column'),
yaxis = dict(title = 'Values'))
fig = go.Figure(data=data, layout=layout)
iplot(fig)
# Compare the distribution of values for at least five columns where there are
# no or few missing values, between the two subsets.
for col in ['ANREDE_KZ','GREEN_AVANTGARDE','FINANZTYP','SEMIO_FAM','HH_EINKOMMEN_SCORE','LP_STATUS_FEIN']:
plot_distribution(col)
(Double-click this cell and replace this text with your own text, reporting your observations regarding missing data in rows. Are the data with lots of missing values are qualitatively different from data with few or no missing values?)
Based on the distribution of the values above we can say that the two subset is qualitatively different, and we cannot simply remove it from the dataset, rather we would need to handle it in a special way.
Checking for missing data isn't the only way in which you can prepare a dataset for analysis. Since the unsupervised learning techniques to be used will only work on data that is encoded numerically, you need to make a few encoding changes or additional assumptions to be able to make progress. In addition, while almost all of the values in the dataset are encoded using numbers, not all of them represent numeric values. Check the third column of the feature summary (feat_info) for a summary of types of measurement.
In the first two parts of this sub-step, you will perform an investigation of the categorical and mixed-type features and make a decision on each of them, whether you will keep, drop, or re-encode each. Then, in the last part, you will create a new data frame with only the selected and engineered columns.
Data wrangling is often the trickiest part of the data analysis process, and there's a lot of it to be done here. But stick with it: once you're done with this step, you'll be ready to get to the machine learning parts of the project!
# How many features are there of each data type?
type_count = feat_info[['attribute', 'type']].groupby('type').count().reset_index().sort_values('attribute', ascending=False)
data = [go.Bar(
x=type_count['type'],
y=type_count['attribute']
)]
layout= dict(title = 'Number of features for each data type',
xaxis = dict(title = 'Data Types'),
yaxis = dict(title = 'Number of features'))
fig = go.Figure(data=data, layout=layout)
iplot(fig)
For categorical data, you would ordinarily need to encode the levels as dummy variables. Depending on the number of categories, perform one of the following:
# Assess categorical variables: which are binary, which are multi-level, and
# which one needs to be re-encoded?
feat_need = list(feat_info['attribute'][(feat_info['type'] == 'categorical') & (feat_info['NULL_RATIO']<=0.18)])
for col in feat_need:
print(azdias_1[col].drop_duplicates())
# Re-encode categorical variable(s) to be kept in the analysis.
#converting binary categorical variable to 1 and 0
azdias_1['OST_WEST_KZ'] = azdias_1['OST_WEST_KZ'].replace({'W':1, 'O':0})
feat_need.remove('OST_WEST_KZ')
encoded = pd.get_dummies(azdias_1[feat_need])
cols_to_use = encoded.columns.difference(azdias_1.columns)
azdias_1 = pd.merge(azdias_1, encoded[cols_to_use], left_index=True, right_index=True, how='left')
(Double-click this cell and replace this text with your own text, reporting your findings and decisions regarding categorical features. Which ones did you keep, which did you drop, and what engineering steps did you perform?) 'AGER_TYP', 'KK_KUNDENTYP', 'TITEL_KZ' categorical features have been already disclosed from the processing of the data due to the high ratio of NULL values.Based on this I've not examined these columns from an encoding perspective. The changes that I've made are the following:
There are a handful of features that are marked as "mixed" in the feature summary that require special treatment in order to be included in the analysis. There are two in particular that deserve attention; the handling of the rest are up to your own choices:
Be sure to check Data_Dictionary.md for the details needed to finish these tasks.
# Investigate "PRAEGENDE_JUGENDJAHRE" and engineer two new variables.
full_map = pd.DataFrame({-1: [np.nan, np.nan],
0: [np.nan, np.nan],
1: [40, 1],
2: [40, 0],
3: [50, 1],
4: [50, 0],
5: [60, 1],
6: [60, 0],
7: [60, 0],
8: [70, 1],
9: [70, 0],
10: [80, 1],
11: [80, 0],
12: [80, 1],
13: [80, 0],
14: [90, 1],
15: [90, 0],
np.nan: [np.nan, np.nan]}).T
full_map.reset_index(inplace=True)
full_map.columns = ['PRAEGENDE_JUGENDJAHRE', 'DECADES', 'MOVEMENTS']
azdias_1 = pd.merge(azdias_1, full_map, how='left', on='PRAEGENDE_JUGENDJAHRE')
# Investigate "CAMEO_INTL_2015" and engineer two new variables.
azdias_1['WEALTH'] = pd.to_numeric(azdias_1['CAMEO_INTL_2015'])//10
azdias_1['LIFE_STAGE'] = pd.to_numeric(azdias_1['CAMEO_INTL_2015'])%10
azdias_1['RURAL'] = pd.cut(azdias_1['WOHNLAGE'], [1,6,9], False, [0,1])
azdias_1['NEIGHBORHOOD_QUAL'] = azdias_1['WOHNLAGE'].replace([7,8], np.nan)
(Double-click this cell and replace this text with your own text, reporting your findings and decisions regarding mixed-value features. Which ones did you keep, which did you drop, and what engineering steps did you perform?)
The two columns 'PRAEGENDE_JUGENDJAHRE' and 'CAMEO_INTL_2015' have been modified to showcase the multiple dimensionality of the features. The rest of the mixed features have been left as it is. WOHNLAGE have been modified to properly represent the buidling quality (1-5) and if a neighbourhood is rural or not (7-8). The rest of the mixed type variables (PLZ8_BAUMAX, LPLEBENSPHASE_FEIN , LP_LEBENSPHASE_GROB) are dropped.
In order to finish this step up, you need to make sure that your data frame now only has the columns that you want to keep. To summarize, the dataframe should consist of the following:
Make sure that for any new columns that you have engineered, that you've excluded the original columns from the final dataset. Otherwise, their values will interfere with the analysis later on the project. For example, you should not keep "PRAEGENDE_JUGENDJAHRE", since its values won't be useful for the algorithm: only the values derived from it in the engineered features you created should be retained. As a reminder, your data should only be from the subset with few or no missing values.
# If there are other re-engineering tasks you need to perform, make sure you
# take care of them here. (Dealing with missing data will come in step 2.1.)
# Do whatever you need to in order to ensure that the dataframe only contains
#deleting unnecessary columns
del(azdias_1['PRAEGENDE_JUGENDJAHRE'])
del(azdias_1['CAMEO_INTL_2015'])
del(azdias_1['CAMEO_DEUG_2015'])
del(azdias_1['CAMEO_DEU_2015'])
del(azdias_1['missing_value'])
del(azdias_1['WOHNLAGE'])
del(azdias_1['PLZ8_BAUMAX'])
del(azdias_1['LP_LEBENSPHASE_FEIN'])
del(azdias_1['LP_LEBENSPHASE_GROB'])
Even though you've finished cleaning up the general population demographics data, it's important to look ahead to the future and realize that you'll need to perform the same cleaning steps on the customer demographics data. In this substep, complete the function below to execute the main feature selection, encoding, and re-engineering steps you performed above. Then, when it comes to looking at the customer data in Step 3, you can just run this function on that DataFrame to get the trimmed dataset in a single step.
def clean_data(df):
"""
Perform feature trimming, re-encoding, and engineering for demographics
data
INPUT: Demographics DataFrame
OUTPUT: Trimmed and cleaned demographics DataFrame
"""
# Put in code here to execute all main cleaning steps:
# convert missing value codes into NaNs, ...
feat_nan_types = feat_info[['missing_or_unknown',
'attribute']].groupby('missing_or_unknown')['attribute'].apply(list).reset_index()
#replacing values which cannot be converted to list by default
feat_nan_types['missing_or_unknown'].replace({'[-1,X]': '[-1,"X"]',
'[-1,XX]': '[-1,"XX"]',
'[XX]': '["XX"]'}, inplace = True)
#converting missing types to lists
feat_nan_types['missing_or_unknown'] = feat_nan_types['missing_or_unknown'].apply(lambda feat: ast.literal_eval(feat))
for feat, attr in zip(feat_nan_types['missing_or_unknown'], feat_nan_types['attribute']):
df[attr] = df[attr].applymap(lambda value: np.nan if value in feat else value)
feat_info['NULL_Value'] = feat_info['attribute'].apply(lambda attr: len(azdias[attr][azdias[attr].isnull()]))
feat_info['NULL_RATIO'] = feat_info['attribute'].apply(lambda attr:
len(azdias[attr][azdias[attr].isnull()]) / len(azdias[attr]) )
# remove selected columns and rows, ...
feat_info_columns = feat_info['attribute'][feat_info['NULL_RATIO']<0.18].values.tolist()
df = df[feat_info_columns].copy()
df['missing_value'] = df.isnull().sum(axis=1)
df_1 = df[df['missing_value'] <= 15].copy()
# select, re-encode, and engineer column values.
df_1['OST_WEST_KZ'] = df_1['OST_WEST_KZ'].replace({'W':1, 'O':0})
feat_need = list(feat_info['attribute'][(feat_info['type'] == 'categorical') & (feat_info['NULL_RATIO']<=0.18)])
feat_need.remove('OST_WEST_KZ')
encoded = pd.get_dummies(df_1[feat_need])
cols_to_use = encoded.columns.difference(df_1.columns)
df_1 = pd.merge(df_1, encoded[cols_to_use], left_index=True, right_index=True, how='left')
full_map = pd.DataFrame({-1: [np.nan, np.nan],
0: [np.nan, np.nan],
1: [40, 1],
2: [40, 0],
3: [50, 1],
4: [50, 0],
5: [60, 1],
6: [60, 0],
7: [60, 0],
8: [70, 1],
9: [70, 0],
10: [80, 1],
11: [80, 0],
12: [80, 1],
13: [80, 0],
14: [90, 1],
15: [90, 0],
np.nan: [np.nan, np.nan]}).T
full_map.reset_index(inplace=True)
full_map.columns = ['PRAEGENDE_JUGENDJAHRE', 'DECADES', 'MOVEMENTS']
df_1 = pd.merge(df_1, full_map, how='left', on='PRAEGENDE_JUGENDJAHRE')
df_1['WEALTH'] = pd.to_numeric(df_1['CAMEO_INTL_2015'])//10
df_1['LIFE_STAGE'] = pd.to_numeric(df_1['CAMEO_INTL_2015'])%10
df_1['RURAL'] = pd.cut(df_1['WOHNLAGE'], [1,6,9], False, [0,1])
df_1['NEIGHBORHOOD_QUAL'] = df_1['WOHNLAGE'].replace([7,8], np.nan)
del(df_1['PRAEGENDE_JUGENDJAHRE'])
del(df_1['CAMEO_INTL_2015'])
del(df_1['CAMEO_DEUG_2015'])
del(df_1['CAMEO_DEU_2015'])
del(df_1['missing_value'])
del(df_1['WOHNLAGE'])
del(df_1['PLZ8_BAUMAX'])
del(df_1['LP_LEBENSPHASE_FEIN'])
del(df_1['LP_LEBENSPHASE_GROB'])
df_1 = df_1.applymap(lambda x: x.strip() if type(x) is str else x)
# Return the cleaned dataframe.
return df_1
azdias = pd.read_csv('Udacity_AZDIAS_Subset.csv', delimiter=';')
azdias_cln = clean_data(azdias)
feature_names = list(azdias_cln.columns)
Before we apply dimensionality reduction techniques to the data, we need to perform feature scaling so that the principal component vectors are not influenced by the natural differences in scale for features. Starting from this part of the project, you'll want to keep an eye on the API reference page for sklearn to help you navigate to all of the classes and functions that you'll need. In this substep, you'll need to check the following:
.fit_transform() method to both fit a procedure to the data as well as apply the transformation to the data at the same time. Don't forget to keep the fit sklearn objects handy, since you'll be applying them to the customer demographics data towards the end of the project.# If you've not yet cleaned the dataset of all NaN values, then investigate and
# do that now.
imputer = Imputer()
imputer_model = imputer.fit(azdias_cln)
azdias_impute = pd.DataFrame(imputer_model.transform(azdias_cln), columns = feature_names)
# Apply feature scaling to the general population demographics data.
scalar = StandardScaler()
scalar_model = scalar.fit(azdias_impute)
azdias_scaled = pd.DataFrame(scalar_model.transform(azdias_impute), columns = feature_names)
(Double-click this cell and replace this text with your own text, reporting your decisions regarding feature scaling.) I've used sklearn imputer function to remove the remaining NaN values, after this I've applied the StandardScaler to normalize the values
On your scaled data, you are now ready to apply dimensionality reduction techniques.
plot() function. Based on what you find, select a value for the number of transformed features you'll retain for the clustering part of the project.# Apply PCA to the data.
pca = PCA()
pca_model= pca.fit(azdias_scaled)
azdias_pca = pca_model.transform(azdias_scaled)
# Investigate the variance accounted for by each principal component.
num_components = len(pca.explained_variance_ratio_)
ind = np.arange(num_components)
vals = pca.explained_variance_ratio_
cumvals = np.cumsum(vals)
trace1 = go.Bar(x=ind,
y=vals)
trace2 = go.Scatter(
x = ind,
y = cumvals,
mode='lines',
)
layout= dict(title = 'Explained Variance per principal component',
xaxis = dict(title = 'Principal Component'),
yaxis = dict(title = 'Variance explained (%)'),
)
data = [trace1, trace2]
fig = go.Figure(data=data, layout=layout)
iplot(fig)
# Re-apply PCA to the data while selecting for number of components to retain.
pca = PCA(n_components=70)
azdias_pca = pca.fit_transform(azdias_scaled)
(Double-click this cell and replace this text with your own text, reporting your findings and decisions regarding dimensionality reduction. How many principal components / transformed features are you retaining for the next step of the analysis?)
I'm retaining 70 components, due to the above plot this component amount will represent at least 95% of the total variances.
Now that we have our transformed principal components, it's a nice idea to check out the weight of each variable on the first few components to see if they can be interpreted in some fashion.
As a reminder, each principal component is a unit vector that points in the direction of highest variance (after accounting for the variance captured by earlier principal components). The further a weight is from zero, the more the principal component is in the direction of the corresponding feature. If two features have large weights of the same sign (both positive or both negative), then increases in one tend expect to be associated with increases in the other. To contrast, features with different signs can be expected to show a negative correlation: increases in one variable should result in a decrease in the other.
# Map weights for the first principal component to corresponding feature names
# and then print the linked values, sorted by weight.
# HINT: Try defining a function here or in a new cell that you can reuse in the
# other cells.
def get_pca_weights(pca, component_number, feature_names):
component_linkage = pd.DataFrame(pca.components_, columns = feature_names)
relevancy = pd.DataFrame(component_linkage.iloc[component_number - 1])
relevancy.columns = ['weights']
relevancy.reset_index(inplace=True)
relevancy.sort_values('weights', ascending=False, inplace=True)
return relevancy
pca_1 = get_pca_weights(pca_model, 1, feature_names)
pca_1
# Map weights for the second principal component to corresponding feature names
# and then print the linked values, sorted by weight.
pca_2 = get_pca_weights(pca_model, 2, feature_names)
pca_2
# Map weights for the third principal component to corresponding feature names
# and then print the linked values, sorted by weight.
pca_3 = get_pca_weights(pca_model, 3, feature_names)
pca_3
(Double-click this cell and replace this text with your own text, reporting your observations from detailed investigation of the first few principal components generated. Can we interpret positive and negative values from them in a meaningful way?)
The first principal component is mainly about wealth and the typical building that familiies are living in. Top features like CAMEO_DEUG_2015, PLZ8_ANTG3, WEALTH, PLZ8_ANTG4 all about personal wealth or the great number of families living in one building. On the negative spectrum we have LP_STATUS_FEIN, FINANZ_MINIMALIST, KBA05_ANTG1 which indicates building with smaller capacities and the related financial typology.
The second principal component is mainly about age and personality . ALTERSKATEGORIE_GROB, FINANZ_VORSORGER, SEMIO_ERL, SEMIO_LUST are about age and personality characteristics. On the negative end we have SEMIO_TRADV, SEMIO_PFLICHT, FINANZ_SPARER, SEMIO_REL. As we age are personality changes as well, this principal component seems to be the mix of the two.
The third principal component all about personality and human characteristics.SEMIO_VERT, SEMIO_SOZ , SEMIO_FAM, SEMIO_KULT are about age and personality characteristics. On the negative end we have ANREDE_KZ, SEMIO_KAEM, SEMIO_DOM, SEMIO_KRIT which are all indicating a different personality.
You've assessed and cleaned the demographics data, then scaled and transformed them. Now, it's time to see how the data clusters in the principal components space. In this substep, you will apply k-means clustering to the dataset and use the average within-cluster distances from each point to their assigned cluster's centroid to decide on a number of clusters to keep.
.score() method might be useful here, but note that in sklearn, scores tend to be defined so that larger is better. Try applying it to a small, toy dataset, or use an internet search to help your understanding.# Over a number of different cluster counts...
cluster_nums = np.arange(1, 30, 5)
dist = []
# run k-means clustering on the data and...
for clust in cluster_nums:
kmeans = KMeans(clust)
kmeans.fit(azdias_pca)
# compute the average within-cluster distances.
dist.append(-kmeans.score(azdias_pca))
# Investigate the change in within-cluster distance across number of clusters.
# HINT: Use matplotlib's plot function to visualize this relationship.
trace2 = go.Scatter(
x = cluster_nums,
y = dist,
mode='lines+markers',
)
layout= dict(title = 'Average Distance Beteen Points and Cluster Center vs. Number of Clusters',
xaxis = dict(title = 'Number of Clusters'),
yaxis = dict(title = 'Average Distance'),
)
data = [trace2]
fig = go.Figure(data=data, layout=layout)
iplot(fig)
# Re-fit the k-means model with the selected number of clusters and obtain
# cluster predictions for the general population demographics data.
kmeans = KMeans(20)
kmeans_best = kmeans.fit(azdias_pca)
azdias_impute['clusters'] = kmeans_best.predict(azdias_pca)
(Double-click this cell and replace this text with your own text, reporting your findings and decisions regarding clustering. Into how many clusters have you decided to segment the population?)
Based on the plot of the KMeans results I've selected 20 clusters. There's no clear 'elbow' to the graph however the average distance does not decrease a lot after 20.
Now that you have clusters and cluster centers for the general population, it's time to see how the customer data maps on to those clusters. Take care to not confuse this for re-fitting all of the models to the customer data. Instead, you're going to use the fits from the general population to clean, transform, and cluster the customer data. In the last step of the project, you will interpret how the general population fits apply to the customer data.
;) delimited.clean_data() function you created earlier. (You can assume that the customer demographics data has similar meaning behind missing data patterns as the general demographics data.).fit() or .fit_transform() method to re-fit the old objects, nor should you be creating new sklearn objects! Carry the data through the feature scaling, PCA, and clustering steps, obtaining cluster assignments for all of the data in the customer demographics data.# Load in the customer demographics data.
customers = pd.read_csv('Udacity_CUSTOMERS_Subset.csv', delimiter=';')
# Apply preprocessing, feature transformation, and clustering from the general
# demographics onto the customer data, obtaining cluster predictions for the
# customer demographics data.
customers_cln = clean_data(customers)
customer_feature_names = list(customers_cln.columns)
customers_impute = pd.DataFrame(imputer_model.transform(customers_cln), columns = customer_feature_names)
customers_scaled = pd.DataFrame(scalar_model.transform(customers_impute), columns = customer_feature_names)
#transform the customers data using pca object
customers_pca = pca.transform(customers_scaled)
#predict clustering using the kmeans object
customers_impute['clusters'] = kmeans_best.predict(customers_pca)
At this point, you have clustered data based on demographics of the general population of Germany, and seen how the customer data for a mail-order sales company maps onto those demographic clusters. In this final substep, you will compare the two cluster distributions to see where the strongest customer base for the company is.
Consider the proportion of persons in each cluster for the general population, and the proportions for the customers. If we think the company's customer base to be universal, then the cluster assignment proportions should be fairly similar between the two. If there are only particular segments of the population that are interested in the company's products, then we should see a mismatch from one to the other. If there is a higher proportion of persons in a cluster for the customer data compared to the general population (e.g. 5% of persons are assigned to a cluster for the general population, but 15% of the customer data is closest to that cluster's centroid) then that suggests the people in that cluster to be a target audience for the company. On the other hand, the proportion of the data in a cluster being larger in the general population than the customer data (e.g. only 2% of customers closest to a population centroid that captures 6% of the data) suggests that group of persons to be outside of the target demographics.
Take a look at the following points in this step:
countplot() or barplot() function could be handy..inverse_transform() method of the PCA and StandardScaler objects to transform centroids back to the original data space and interpret the retrieved values directly.# Compare the proportion of data in each cluster for the customer data to the
# proportion of data in each cluster for the general population.
azdias_impute['row_count'] = 1
azdias_clusters_cnt = azdias_impute[['clusters', 'row_count']].groupby('clusters').count().reset_index()
azdias_clusters_cnt['ratio'] = azdias_clusters_cnt['row_count']/sum(azdias_clusters_cnt['row_count'])
azdias_clusters_cnt['dataset'] = 'General'
# customers demographics
customers_impute['row_count'] = 1
customers_clusters_cnt = customers_impute[['clusters', 'row_count']].groupby('clusters').count().reset_index()
customers_clusters_cnt['ratio'] = customers_clusters_cnt['row_count']/sum(customers_clusters_cnt['row_count'])
customers_clusters_cnt['dataset'] = 'Customers'
trace1 = go.Bar(
x=azdias_clusters_cnt['clusters'],
y=azdias_clusters_cnt['ratio'],
name='General'
)
trace2 = go.Bar(
x=customers_clusters_cnt['clusters'],
y=customers_clusters_cnt['ratio'],
name='Customers'
)
data = [trace1, trace2]
layout = dict(title = 'Cluster Visualizations for General and Customer Demographics',
xaxis = dict(title = 'Clusters'),
yaxis = dict(title = 'Percentage'),
barmode='group'
)
fig = go.Figure(data=data, layout=layout)
iplot(fig)
cluster_over_need = pd.DataFrame(customers_impute[customers_impute['clusters']==13].columns)
cluster_over_need.columns= ['columns']
# What kinds of people are part of a cluster that is overrepresented in the
# customer data compared to the general population?
13
cluster_over_need['most_frequent_value'] = cluster_over_need['columns'].apply(lambda col:
customers_impute[col][customers_impute['clusters']==13].mode().iloc[0])
cluster_over_need
# What kinds of people are part of a cluster that is underrepresented in the
# customer data compared to the general population?
12
cluster_under_need = pd.DataFrame(customers_impute[customers_impute['clusters']==12].columns)
cluster_under_need.columns= ['columns']
cluster_under_need['most_frequent_value'] = cluster_under_need['columns'].apply(lambda col: customers_impute[col][customers_impute['clusters']==12].mode().iloc[0])
cluster_under_need
(Double-click this cell and replace this text with your own text, reporting findings and conclusions from the clustering analysis. Can we describe segments of the population that are relatively popular with the mail-order company, or relatively unpopular with the company?)
segments of the population that are relatively popular with the mail-order company is cluster 13 : most of them are and elderly people(between 40 and 60 years old), additionally this group can be considered in a positive financial status, living in a multiperson household, with a sufficient investment mindset and financial background to do so.
segments of the population that are relatively unpopular with the mail-order company is cluster 12: While the age is similar to the previously highlighted cluster, this group is from the lower middle class with poorer financial status, and with lack of investment fund and attitude
Congratulations on making it this far in the project! Before you finish, make sure to check through the entire notebook from top to bottom to make sure that your analysis follows a logical flow and all of your findings are documented in Discussion cells. Once you've checked over all of your work, you should export the notebook as an HTML document to submit for evaluation. You can do this from the menu, navigating to File -> Download as -> HTML (.html). You will submit both that document and this notebook for your project submission.